﻿using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kinlo.MESDocking.MQTT
{
    public static class MqttHelper
    {

        #region 同步
        //private static IMqttClient _mqttClient;
        //// 连接MQTT服务器并发送消息的方法
        //public static void MQTTSendMessage(string brokerAddress, string topic, string message)
        //{
        //    try
        //    {
        //        if (_mqttClient == null || !_mqttClient.IsConnected)
        //        {
        //            if (!ConnectToMqttServer(brokerAddress)) return;
        //        }

        //        SendMessage(topic, message);
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"错误: {ex.Message}");
        //    }
        //}

        //// 连接到MQTT服务器的方法
        //private static bool ConnectToMqttServer(string brokerAddress)
        //{
        //    var factory = new MqttFactory();
        //    _mqttClient = factory.CreateMqttClient();
        //    var options = new MqttClientOptionsBuilder()
        //        .WithTcpServer(brokerAddress)
        //        .Build();

        //    try
        //    {
        //        // 连接到MQTT服务器
        //        _mqttClient.ConnectAsync(options).Wait(); // 阻塞等待连接完成

        //        // 连接成功
        //        Console.WriteLine("成功连接到MQTT服务器");
        //        return true;

        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"连接到MQTT服务器时发生错误: {ex.Message}");
        //        // 在这里处理连接错误，可以执行重试或其他适当的操作
        //        return false;
        //    }
        //}

        //// 发送消息到指定主题的方法
        //private static void SendMessage(string topic, string message)
        //{
        //    var mqttMessage = new MqttApplicationMessageBuilder()
        //        .WithTopic(topic)
        //        .WithPayload(message)
        //        .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
        //        .Build();

        //    // 发布消息
        //    _mqttClient.PublishAsync(mqttMessage).Wait(); // 使用 .Wait() 阻塞等待消息发布完成
        //    Console.WriteLine($"消息已发送到主题 {topic}: {message}");
        //}
        #endregion

        #region 异步
        private static IMqttClient _mqttClient;

        // 连接MQTT服务器并发送消息的方法
        public static async Task ConnectAndSendMessageAsync(string brokerAddress, int port, string topic, string message)
        {
            try
            {
                if (_mqttClient == null || !_mqttClient.IsConnected)
                {
                    await ConnectToMqttServerAsync(brokerAddress, port);
                }

                await SendMessageAsync(topic, message);
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"错误: {ex.Message}");
            }
        }

        // 连接到MQTT服务器的方法
        private static async Task ConnectToMqttServerAsync(string brokerAddress, int port)
        {
            try
            {
                var factory = new MqttFactory();
                _mqttClient = factory.CreateMqttClient();
                var options = new MqttClientOptionsBuilder()
                    .WithTcpServer(brokerAddress, port)
                    .Build();


                // 连接到MQTT服务器
                await _mqttClient.ConnectAsync(options);
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"连接错误: {ex}");
            }

        }

        // 发送消息到指定主题的方法
        private static async Task SendMessageAsync(string topic, string message)
        {
            var mqttMessage = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(message)
                .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                .Build();

            // 发布消息
           await _mqttClient.PublishAsync(mqttMessage);

            //Console.WriteLine($"消息已发送到主题 {topic}: {message}");
        }
        #endregion
    }
}
